# -*- coding: utf-8 -*-

# Bliotecas padrões
from django.db import models
from django.contrib.admin.models import User
from django.forms import ModelForm
from django.contrib.localflavor.br.br_states import STATE_CHOICES
from django.contrib.localflavor.br.forms import *
from django.contrib.auth.models import Permission
from django.utils.translation import ugettext as _
import exceptions
from django.forms.extras.widgets import *
from django import forms
from django.forms.extras.widgets import SelectDateWidget
from datetime import *
from django.db.models import signals

# Bibliotecas externas

# Bibliotecas das apps
from myproject.settings import MEDIA_URL, MEDIA_ROOT
from choices import *

# Models
from myproject.aula.models import *

class Cadastro(models.Model):
    #relacionamento com os user do django
    user = models.ForeignKey(User, blank=True, null=True, editable=False)
    
    login = models.CharField(verbose_name=u'Login',max_length=16,unique=True)
    senha = models.CharField(_('password'),max_length=10)
    nome = models.CharField(verbose_name=u'Nome',max_length=16)
    sobrenome = models.CharField(verbose_name=u'Sobrenome',max_length=16)
    email = models.EmailField(verbose_name=u'E-mail',max_length=32, blank=True)
    status = models.BooleanField(_('active'), default=True)
    
    cpf = models.CharField(verbose_name=u'CPF',max_length=14)
    rg = models.CharField(verbose_name=u'RG',max_length=9)
    dataNascimento = models.DateField(verbose_name=u'Data de nascimento')
    endereco = models.CharField(verbose_name=u'Endereço',max_length=64)
    cep = models.CharField(verbose_name=u'Cep',max_length=9)
    bairro = models.CharField(verbose_name=u'Bairro',max_length=16)
    pais = models.CharField(verbose_name=u'País',max_length=16,choices=COUNTRY_CHOICES,default='1')
    estado = models.CharField(verbose_name=u'Estado',max_length=2,choices=STATE_CHOICES)
    cidade = models.CharField(verbose_name=u'Cidade',max_length=16)
    telefone = models.CharField(verbose_name=u'Telefone',max_length=14, blank=True, null=True)
    celular = models.CharField(verbose_name=u'Celular',max_length=14, blank=True, null=True)
  
    class Meta:
  
        ordering = ['-id']
        permissions = (
          ("per_aluno", "Um aluno"),
          ("per_professor", "Um professor"),
          ("per_administrador", "Um administrador"),
        )

    def save(self):
        if not self.id:
            usr = User.objects.filter(username=self.login)
            if usr:
                u = usr[0]
            else:
                u = User.objects.create_user(self.login,self.email,self.senha)
            u.first_name = self.nome
            u.last_name = self.sobrenome
            u.is_active = self.status 
            u.save()
            self.user = u
        else:
            self.user.username = self.login
            self.user.email = self.email
            self.user.set_password(self.senha)
            self.user.first_name = self.nome
            self.user.last_name = self.sobrenome
            self.user.is_active = self.status 
            self.user.save()
        super(Cadastro, self).save()
        # Adiciono as permissões
        if self.tipo == '1':
            self.user.user_permissions.add( Permission.objects.get(codename='per_aluno') )
        elif self.tipo == '2':
            self.user.user_permissions.add(Permission.objects.get(codename='per_professor'))
        elif self.tipo == '3':
            self.user.user_permissions.add(Permission.objects.get(codename='per_administrador'))    

    def __unicode__ (self):
        return self.nome 

class Alunos(Cadastro):

    tipo = models.CharField(max_length=1,editable=False,default='1')
    curso = models.ManyToManyField(Curso,verbose_name=u'Curso')
    foto = ImageWithThumbsField(upload_to='arquivos/aluno/%Y/%m/%d',max_length=100)

    nomeResponsavel = models.CharField(verbose_name=u'Nome do responsável',max_length=16, blank=True, null=True)
    sobrenomeResponsavel = models.CharField(verbose_name=u'Sobrenome do responsável',max_length=16, blank=True, null=True)
    cpfResponsavel = models.CharField(verbose_name=u'CPF do responsável',max_length=14, blank=True, null=True)
    rgResponsavel = models.CharField(verbose_name=u'RG do responsável',max_length=9, blank=True, null=True)
    dataNascimentoResponsavel = models.DateField(verbose_name=u'Data de nascimento', blank=True, null=True)
    enderecoResponsavel = models.CharField(verbose_name=u'Endereço do responsável',max_length=64, blank=True, null=True)
    cepResponsavel = models.CharField(verbose_name=u'Cep do responsável',max_length=9, blank=True, null=True)
    bairroResponsavel = models.CharField(verbose_name=u'Bairro do responsável',max_length=16, blank=True, null=True)
    paisResponsavel = models.CharField(verbose_name=u'País do responsável',max_length=16, blank=True, null=True)
    estadoResponsavel = models.CharField(verbose_name=u'Estado do responsável',max_length=2,choices=STATE_CHOICES, blank=True, null=True)
    cidadeResponsavel = models.CharField(verbose_name=u'Cidade do responsável',max_length=16, blank=True, null=True)
    telefoneResponsavel = models.CharField(verbose_name=u'Telefone do responsável',max_length=14, blank=True, null=True)
    emailResponsavel = models.EmailField(verbose_name=u'E-mail do responsável',max_length=32, blank=True, null=True)
    
    def __unicode__ (self):
        return self.nome
    
    class Meta:
        verbose_name = u'Cadastro Aluno'
        verbose_name_plural = u'Cadastro Alunos'
        ordering = ['nome']

class AulaAluno(models.Model):
  
    aluno = models.ForeignKey(Alunos,verbose_name=u'Aluno')
    curso = models.ForeignKey(Curso,verbose_name=u'Curso')
    aula = models.ForeignKey(Aula,verbose_name=u'Aula',blank=True)
    horaInicial = models.TimeField(verbose_name=u'Hora inicial',blank=True,default=datetime.now().time)
    horaFinal = models.TimeField(verbose_name=u'Hora final',blank=True,default=datetime.now().time)
    data = models.DateField(verbose_name=u'Data',default=date.today,blank=True,null=True)
      
    class Meta:
        ordering = ['-id']

    class Meta:
      verbose_name = u'Cadastro aula do aluno'
      verbose_name_plural = u'Cadastro aulas dos alunos' 
      ordering = ['-id']

def aulaAluno_post_save(instance, sender, **kwargs):
    '''
        Cria a tabela de presenca do sistema.
    '''

    if Presenca.objects.filter(aluno__id=instance.aluno.id,
                               curso__id=instance.curso.id,
                               aula__id=instance.aula.id,).count() == 0:
        presenca = Presenca(aluno=instance.aluno,
                            curso=instance.curso,
                            aula=instance.aula,)
        presenca.save()
    return

signals.post_save.connect(aulaAluno_post_save, sender=AulaAluno)

class Presenca(models.Model):
  
    aluno = models.ForeignKey(Alunos,verbose_name=u'Aluno')
    curso = models.ForeignKey(Curso,verbose_name=u'Curso')
    aula = models.ForeignKey(Aula,verbose_name=u'Aula',blank=True)
    presenca = models.BooleanField(default=False,verbose_name=u'Concluído?')

class Nota(models.Model):
  
    aluno = models.ForeignKey(Alunos,verbose_name=u'Aluno')
    curso = models.ForeignKey(Curso,verbose_name=u'Curso')
    descricao = models.CharField(verbose_name=u'Descrição',max_length=32,unique=True)
    notaAluno = models.CharField(verbose_name=u'Nota do aluno',max_length=5)
    notaTotal = models.CharField(verbose_name=u'Nota total',max_length=5)
    
    def __unicode__ (self):
        return self.descricao

    class Meta:
        verbose_name = u'Nota'
        verbose_name_plural = u'Notas'
        ordering = ['descricao']

class Professor(Cadastro):
    
    curriculo = models.FileField(upload_to='arquivos/professor/',blank=True)
    foto = ImageWithThumbsField(upload_to='arquivos/professor/%Y/%m/%d',max_length=100)

    tipo = models.CharField(max_length=1,editable=False,default=`2`)
    curso = models.ManyToManyField(Curso)

    def __unicode__ (self):
        return self.nome

    class Meta:
        verbose_name = u'Cadastro Professor'
        verbose_name_plural = u'Cadastro Professores'
        ordering = ['nome']

class CursosProfessor(models.Model):
    
    professor = models.ForeignKey(Professor, blank=True, null=True, editable=False)
    nome = models.CharField(verbose_name=u'Nome do curso',max_length=32, blank=True)
    instituicao = models.CharField(verbose_name=u'Instituição',max_length=32, blank=True)
    duracao = models.CharField(verbose_name=u'Duração',max_length=32, blank=True)

    def __unicode__ (self):
        return self.nome

    class Meta:
        verbose_name = u'Cursos do Professor'
        verbose_name_plural = u'Cursos dos Professores'
        ordering = ['nome']	  

class Administrador(Cadastro):
    
    tipo = models.CharField(max_length=1,editable=False,default=`3`)

    def __unicode__ (self):
        return self.nome
    
    class Meta:
        verbose_name = u'Cadastro Administrador'
        verbose_name_plural = u'Cadastro Administradores'
        ordering = ['nome']	    